package cn.zwy.实战;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import cn.zwy.asm.MyClassLoader;
import cn.zwy.bean.UserBean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;

public class ASMJson {
    private Class<?> targetClass;
    public static MyClassLoader classLoader = new MyClassLoader("myClassLoader");

    public Class<?> getTargetClass() {
        return targetClass;
    }

    public void setTargetClass(Class<?> targetClass) {
        this.targetClass = targetClass;
    }
    
    public Class<?> newProxyClass() throws IOException{
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        ClassVisitor cv = new ASMJSONClassVisitor(cw, targetClass);
        String name = targetClass.getName().replace(".", "/") + ".class";
        ClassReader cr = new ClassReader(targetClass.getClassLoader().getResourceAsStream(name));
        cr.accept(cv, 0);
        byte[] classByteArr = cw.toByteArray();
        FileOutputStream fos = new FileOutputStream(new File("D:\\bytecode", targetClass.getName() +"_JSON.class"));
        fos.write(classByteArr, 0, classByteArr.length);
        fos.flush();
        fos.close();
        return classLoader.loadClassByte(targetClass.getName() +"_JSON", classByteArr);
    }
    
    public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException {
        ASMJson asmJson = new ASMJson();
        asmJson.setTargetClass(UserBean.class);
        UserBean bean = new UserBean();
        bean.setEmail("568452976@qq.com");
        bean.setUsername("zhaoweiyong");
        bean.setAge(25);
        bean.setAmount(new BigDecimal("50.00"));
        ASMJsonInterface asmJsonInterface = (ASMJsonInterface) asmJson.newProxyClass().newInstance();
        System.out.println(asmJsonInterface.toJSON(bean));
        
        long start = System.currentTimeMillis();
        
        for(int i=0; i<10;i++){
            asmJsonInterface.toJSON(bean);
        }
        
        long end = System.currentTimeMillis();
        
        System.out.println(end - start +"毫秒");
    }
}
